package com.smf.lsc.security.util;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.smf.lsc.security.converter.MyUserDetails;

/**
 * 获取当前登录用户工具类 Created on 2021/11/19.
 *
 * @author ln
 * @since 1.0
 */
public class AuthUserUtil {

	private static final String GATEWAY_ADD_HEAD = "smf-gateway";
	private static final String GATEWAY_PREMIS_FLAG = "PermissionUrl";
	private static final String NO_USER_KEY="anonymousUser";
	public static final String USER_INFO_KEY = "userinfo";
	
	private static final ThreadLocal<MyUserDetails> myUserContext = new ThreadLocal<MyUserDetails>();

	public static MyUserDetails getCurrentUser() {
		try {
			ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
					.getRequestAttributes();
			if(attributes==null)
			{
				return getRpcCurrentUser();
			}
			else
			{
				// fegin/restful请求根据header获取
				HttpServletRequest request = attributes.getRequest();
				String userInfo = request.getHeader(GATEWAY_ADD_HEAD);
				if (!StringUtils.isEmpty(userInfo)) {
					if (GATEWAY_PREMIS_FLAG.equals(userInfo)) {
						return new MyUserDetails();
					} else {
						JSONObject userJson = JSONObject.parseObject(userInfo);
						MyUserDetails currentUser = JSON.toJavaObject(userJson, MyUserDetails.class);
						return currentUser;
					}
				} else {
					// dubbo请求根据threadLoacl获取
					return getRpcCurrentUser();
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			return new MyUserDetails();
		}

	}
	
	private static MyUserDetails getRpcCurrentUser()
	{
		SecurityContext securityContext = SecurityContextHolder.getContext();
		if(securityContext.getAuthentication()==null || NO_USER_KEY.equals(securityContext.getAuthentication().getPrincipal()))
		{
			if(myUserContext.get()!=null)
			{
				return myUserContext.get();
			}
			return new MyUserDetails();
		}
		return (MyUserDetails) securityContext.getAuthentication().getPrincipal();
	}

	/**
	 * 存放用户信息
	 *
	 * @param user
	 */
	public static void set(JSONObject user) {
		myUserContext.set(JSON.toJavaObject(user, MyUserDetails.class));
	}

	/**
	 * 获取用户信息
	 *
	 * @return
	 */
	public static MyUserDetails get() {
		return myUserContext.get();
	}
	
	/**
	 * 清除用户信息
	 *
	 * @param user
	 */
	public static void remove() {
		myUserContext.remove();
	}

}
